<template>
  <div class="page-container">
    <ex_super_table_page v-bind="option" ref="SuperTablePage" :tableVisible="table_visible">

      <template v-slot:table_footer>
        <el-table-column v-for="(item, index) in table_footer" :key="index" :label="item" width="150" align="center">
          <el-table-column label="S" width="50" align="center" :prop="`${item},s`"
            :formatter="(r, c, v, i) => formatter(r, item, 's')">
          </el-table-column>
          <el-table-column label="M" width="50" align="center" :prop="`${item},m`"
            :formatter="(r, c, v, i) => formatter(r, item, 'm')">
          </el-table-column>
          <el-table-column label="SM" width="50" align="center" :prop="`${item},sm`"
            :formatter="(r, c, v, i) => formatter(r, item, 'sm')">
          </el-table-column>
        </el-table-column>

      </template>
    </ex_super_table_page>
    <dialog_time_interval_cfg ref="dialog_time_interval_cfg" typeCode="WAREHOUSE_SHIFT_TASK"
      @success="$refs.SuperTablePage.reload()" />
  </div>
</template>

<script>
import moment from 'moment-mini-ts'
import superTablePageFunction from "@/mixin/super-table-page-function";

import dialog_time_interval_cfg from './dialog_time_interval_cfg.vue'
export default {
  title: 'label_work_change',
  mixins: [  superTablePageFunction,],
  components: { dialog_time_interval_cfg },
  data() {
    return {
      table_visible: true,
      option: {
        search: {
          default: {
            startTime: moment().set({ 'hours': 0, 'minutes': 0, 'seconds': 0, 'milliseconds': 0 }).subtract(3, 'day').valueOf(),
            endTime: moment().set({ 'hours': 23, 'minutes': 59, 'seconds': 59, 'milliseconds': 999 }).valueOf(),

          },
          rules: {
            startTime: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
            endTime: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
          },
          model: [
            {
              label: "label_warehouse_area", key: "areaId", type: 'base_area_select', keyExtra: { code: 'areaCode' },
            },
            {
							label: 'label_create_order_date',
							key: 'startTime',
							type: 'date-picker',
							attrs: { type: 'datetime' },
							render: (h, { data, item }) => {
								const value = data[item.key];
								const limitKey = 'endTime';
								const limitValue = data[limitKey];

								return (
									<ex_super_input
										value={value}
										onInput={(e) => this.$set(data, item.key, e)}
										type="date-picker"
										placeholder="label_start_time"
										attrs={{ clearable: false, type: 'datetime' }}
										pickerOptions={{
											disabledDate: (date) => {
												if (limitValue) {
													if (limitValue < date.getTime()) {
														return true;
													} else if (
														moment(limitValue)
															.subtract(1, 'months')
															.valueOf() > date.getTime()
													) {
														return true;
													}
												}
												return false;
											},
										}}
									/>
								);
							},
						},
						{
							label: '~',
							key: 'endTime',
							type: 'date-picker',
							attrs: { type: 'datetime' },
							render: (h, { data, item }) => {
								const value = data[item.key];
								const limitKey = 'startTime';
								const limitValue = data[limitKey];

								return (
									<ex_super_input
										value={value}
										onInput={(e) => this.$set(data, item.key, e)}
										type="date-picker"
										placeholder="label_end_time"
										attrs={{ clearable: false, type: 'datetime', 'default-time': '23:59:59' }}
										pickerOptions={{
											disabledDate: (date) => {
												if (limitValue) {
													if (limitValue < date.getTime()) {
														return true;
													} else if (
														moment(limitValue)
															.add(1, 'months')
															.valueOf() < date.getTime()
													) {
														return true;
													}
												}
												return false;
											},
										}}
									/>
								);
							},
						},
          ],
        },
        actionExtra: [
          {
            label: "label_pms_time_period_cfg", click: () => {
              this.$refs.dialog_time_interval_cfg.show()
            }
          },
          { label: 'label_export', attrs: { type: "primary" }, click: this.exportExcel },

        ],
        table: {
          url: "/wms-api/outbound/OutboundOverseasOrderRpc/queryWmsOutboundOrderTaskAreaCountStat.json",
          urlParams: {
            reprotType: 'WAREHOUSE_SHIFT_TASK'
          },
          urlDataHandle: this.dataHandle,
          autoPage: false, emptySlot: false,
          attrs: {
            "show-summary": true,
            "summary-method": this.getSummaries,
          },
          model: [
            {
              key: 'areaCode', label: 'label_warehouse_area', width: 130, 'show-overflow-tooltip': true,
            },
          ],

        }
        ,

      },
      table_footer: [],
    }
  },
  methods: {
    getSummaries(params) {
      const { columns, data } = params;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        } else if (index === 1) {
          sums[index] = '';
          return;
        }
        if (column.property&&column.property.includes(",")) {
          const keys = column.property.split(",")
          const values = data.map(item => Number(item[keys[0]][keys[1]]));
          if (!values.every(value => Number.isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
          } else {
            sums[index] = 'N/A';
          }
        }

      });

      return sums;
    },
    formatter(r, item, key) {
      return r[item] ? r[item][key] : '-'
    },
    fixTimeKey(it) {
      return `${it.dateStr} ${it.startTime}-${it.endTime}`
    },
    dataHandle(res) {
      const list = res.data.rows
      const timeKeys = _.groupBy(list, (v) => {
        v.timeKey = this.fixTimeKey(v)
        return v.timeKey
      })
      this.table_footer = Object.keys(timeKeys)
      this.table_visible = false
      this.$nextTick(() => {
        this.table_visible = true
      })
      const out = {}
      list.forEach(it => {
        if (it.areaCode) {
          if (!out[it.areaCode]) {
            out[it.areaCode] = { areaCode: it.areaCode }
          }
          out[it.areaCode][this.fixTimeKey(it)] = {
            s: it.scount,
            m: it.mcount,
            sm: it.smCount,
          }
        }

      })
      return Object.values(out)
    },
    exportExcel() {
      this.$downloadFile({
        loading: true,
        url: '/wms-api/outbound/OutboundOverseasOrderRpc/exportWmsOutboundOrderTaskAreaCountStat.json',
        data: {
          ...this.$refs.SuperTablePage.getSearchFormData()
        },
      })
    },

  }

}
</script>

<style scoped></style>
